package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.exception.ServiceException;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.nursing.domain.dto.CheckInApplyDto;
import com.zzyl.nursing.domain.dto.CheckInConfigDto;
import com.zzyl.nursing.domain.dto.CheckInContractDto;
import com.zzyl.nursing.domain.dto.CheckInElderDto;
import com.zzyl.nursing.domain.pojo.*;
import com.zzyl.nursing.domain.vo.CheckInConfigVo;
import com.zzyl.nursing.domain.vo.CheckInDetailVo;
import com.zzyl.nursing.domain.vo.CheckInElderVo;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.service.ICheckInService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.util.Arrays;
import java.util.List;

/**
 * 入住Service业务层处理
 *
 * @author alexis
 * @date 2025-05-19
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;
    @Autowired
    private ContractMapper contractMapper;
    @Autowired
    private BedMapper bedMapper;

    /**
     * 查询入住
     *
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return checkInMapper.selectById(id);
    }

    /**
     * 查询入住列表
     *
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return checkInMapper.insert(checkIn);
    }

    /**
     * 修改入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return checkInMapper.updateById(checkIn);
    }

    /**
     * 批量删除入住
     *
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return checkInMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除入住信息
     *
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return checkInMapper.deleteById(id);
    }

    /**
     * 新增入住申请
     *
     * @param checkInApplyDto
     */
    @Override
    public void addCheckIn(CheckInApplyDto checkInApplyDto) {
        //一、校验
        //1.判断老人是否入住 :  select * from elder where name = ? and id_card_no = ? and status = 1 ;
        CheckInElderDto checkInElderDto = checkInApplyDto.getCheckInElderDto();
        Elder elderDb = elderMapper.selectOne(Wrappers.<Elder>lambdaQuery()
                .eq(Elder::getName, checkInElderDto.getName())
                .eq(Elder::getIdCardNo, checkInElderDto.getIdCardNo())
                .eq(Elder::getStatus, 1));
        if (ObjectUtil.isNotNull(elderDb)) {
            throw new ServiceException("老人已入住,请勿重复申请");
        }

        //二、新增或更新
        //1.更新床位状态
        CheckInConfigDto checkInConfigDto = checkInApplyDto.getCheckInConfigDto(); //获取入住配置对象(含床位id)
        Bed bed = bedMapper.selectById(checkInConfigDto.getBedId()); //根据床位id搜索床对象
        bed.setBedStatus(1); //给床对象新增设置床位状态
        bedMapper.updateById(bed);
        //2.新增或更新老人
        Elder insertOrUpdateElder = elderMapper.selectOne(Wrappers.<Elder>lambdaQuery()
                .eq(Elder::getName, checkInElderDto.getName())
                .eq(Elder::getIdCardNo, checkInElderDto.getIdCardNo())
                .ne(Elder::getStatus, 1));  //获取一个老人的中间态

        Elder elder = new Elder();
        BeanUtil.copyProperties(checkInElderDto, elder);
        elder.setBedId(checkInConfigDto.getBedId());
        elder.setBedNumber(bed.getBedNumber());
        //判断这个中间态是否存在
        if (ObjectUtil.isNotNull(insertOrUpdateElder)) {
            //中间态不为空,则代表老人存在,只做更新,这种更新只做换房换床等服务
            elder.setId(insertOrUpdateElder.getId());
            elderMapper.updateById(elder);
        } else {
            elderMapper.insert(elder);
        }

        //3.新增签约办理
        CheckInContractDto contractDto = checkInApplyDto.getCheckInContractDto();
        //3.1补全CheckInContractDto中缺失的表内要求必填的属性
        Contract contract = BeanUtil.toBean(contractDto, Contract.class);
        contract.setElderId(elder.getId()); //补全老人ID
        contract.setElderName(elder.getName()); //补全老人姓名
        contract.setStartDate(checkInConfigDto.getStartDate()); //补全合同起始时间
        contract.setEndDate(checkInConfigDto.getEndDate()); //补全合同终止时间
        contract.setStatus(checkInConfigDto.getStartDate().isBefore(LocalDateTime.now()) ? 1 : 0); //补全合同状态,根据合同起始时间与当前时间做对比
        contract.setContractNumber("HT" + CodeGenerator.generateContractNumber());//调用合同编码工具类生成编码,采用类的静态方法调用,并加上合同前缀
        contractMapper.insert(contract); //将补全了基础属性的合同对象加入到合同表中

        //4.新增入住
        CheckIn checkIn = BeanUtil.toBean(checkInConfigDto, CheckIn.class); //将config的dto对象属性赋值给CheckIn并创建
        checkIn.setElderName(elder.getName()); //创建后根据数据库表字段,与CheckIn实体类做对比,补全缺失属性
        checkIn.setElderId(elder.getId()); //创建后根据数据库表字段,与CheckIn实体类做对比,补全缺失属性
        checkIn.setIdCardNo(elder.getIdCardNo()); //创建后根据数据库表字段,与CheckIn实体类做对比,补全缺失属性
        checkIn.setBedNumber(elder.getBedNumber()); //创建后根据数据库表字段,与CheckIn实体类做对比,补全缺失属性
        checkInMapper.insert(checkIn);

        //5.新增入住配置
        CheckInConfig checkInConfig = BeanUtil.toBean(checkInConfigDto, CheckInConfig.class); //同理如上
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigMapper.insert(checkInConfig);

    }

    /**
     * 查询入住详情
     *
     * @param id
     */
    @Override
    public CheckInDetailVo detail(Long id) {
        //0.根据入住id获取checkIn对象
        CheckIn checkIn = checkInMapper.selectById(id);

        //1.查询checkInElderVo字段属性(根据checkIn的老人ID获取老人对象)
        Elder elder = elderMapper.selectElderById(checkIn.getElderId());
        //1.1复制给vo对象
        CheckInElderVo checkInElderVo = BeanUtil.toBean(elder, CheckInElderVo.class);
        //1.2根据复制属性后的vo对象中的出生日期获取年龄并赋值
        LocalDate currentDate = LocalDate.now();
        int age = Period.between(LocalDate.parse(checkInElderVo.getBirthday()), currentDate).getYears();
        checkInElderVo.setAge(age);

        //2.查询elderFamilyVoList字段属性

        //3.查询checkInConfigVo字段属性
        CheckInConfig checkInConfig = checkInConfigMapper.selectById(id);
        CheckInConfigVo checkInConfigVo = BeanUtil.toBean(checkInConfig, CheckInConfigVo.class);
        //3.1补全属性
        checkInConfigVo.setStartDate(checkIn.getStartDate());
        checkInConfigVo.setEndDate(checkIn.getEndDate());
        checkInConfigVo.setBedNumber(checkIn.getBedNumber());

        //4.查询contract字段属性(selectById方法只能适用于主键id)
        Contract contract = contractMapper.selectOne(Wrappers.<Contract>lambdaQuery()
                .eq(Contract::getElderId, checkIn.getElderId())
                .eq(Contract::getStatus, 1));

        //5.创建最终回传Vo对象,将以上获取的属性赋值
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        checkInDetailVo.setCheckInElderVo(checkInElderVo);
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
        checkInDetailVo.setContract(contract);

        return checkInDetailVo;
    }
}
